package cn.shyouchi.wuguanjia.android.ui.completeinfo;

import android.content.Context;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Base64;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.shyouchi.wuguanjia.android.api.hanvon.HanvonApi;
import cn.shyouchi.wuguanjia.android.model.IdCardEntity;
import cn.shyouchi.wuguanjia.android.model.IdCardReverseEntity;
import cn.shyouchi.wuguanjia.android.model.User;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Eenie on 2016/10/13 at 13:30
 * Email: 472279981@qq.com
 * Des:
 */

public class BasicInfoPresenter implements BasicInfoContract.Presenter {

    Context mContext;
    BasicInfoContract.View mView;
    HanvonApi mHanvonApi;
    User mUser;

    IdCardEntity en;

    public BasicInfoPresenter(Context context, User user) {
        this.mContext = context;
        mHanvonApi = new HanvonApi(mContext);
        this.mUser = user;
    }

    @Override
    public void verifyIDCard(final String frontImgPath, final String reverseImgPath) {
        if (TextUtils.isEmpty(frontImgPath)) {
            mView.showToast("请拍摄身份证人像面");
            return;
        }
        if (TextUtils.isEmpty(reverseImgPath)) {
            mView.showToast("请拍摄身份证国徽面");
            return;
        }


        mHanvonApi.identidyIdCard(frontImgPath)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<IdCardEntity>(mContext) {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mHanvonApi.identidyIdCardReverse(reverseImgPath)
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new ProgressSubscriber<IdCardReverseEntity>(mContext) {
                                    @Override
                                    public void onCompleted() {
                                        super.onCompleted();
                                        mView.verifySuccess(mUser);
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        super.onError(e);
                                        mView.showToast("身份证国徽面失败，请重拍");
                                    }

                                    @Override
                                    public void onNext(IdCardReverseEntity data) {
                                        try {
                                            mUser.setName(en.name);
                                            mUser.setGender(en.gender);
                                            mUser.setAddress(en.address);
                                            mUser.setPeople(en.people);
                                            mUser.setNumber(en.idnumber);
                                            mUser.setBirthday(String.format("%s-%s-%s", en.byear, en.bmonth, en.bday));
                                            mUser.setIdCardPositiveImagePath(base64ToFile(en.croppedImage).getAbsolutePath());
                                            mUser.setIdCardHeadImagePath(base64ToFile(en.headImage).getAbsolutePath());
                                            mUser.setAuthority(data.authority);
                                            mUser.setValidate(data.validdate);
                                            mUser.setIdCardNegativeImagePath(base64ToFile(data.croppedImage).getAbsolutePath());
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        mView.showToast("身份证人像面验证失败，请重拍");
                    }

                    @Override
                    public void onNext(IdCardEntity entity) {
                        en = entity;
                    }
                });
    }


    private File base64ToFile(String base64) throws IOException {
        byte[] decodedString = Base64.decode(base64, Base64.DEFAULT);
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(imageFileName, ".jpg", storageDir);
        FileOutputStream fos = new FileOutputStream(image);
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fos);
        bufferedOutputStream.write(decodedString);
        bufferedOutputStream.close();
        return image;
    }


    @Override
    public void attachView(@NonNull BasicInfoContract.View view) {
        this.mView = view;
    }

    @Override
    public void detachView() {

    }
}
